<template>
  <view class="today-container">
    <!-- 顶部统计 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-value">{{todayStats.totalOrders}}</text>
        <text class="stat-label">总订单数</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">¥{{todayStats.totalIncome}}</text>
        <text class="stat-label">总收入</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{todayStats.paidOrders}}</text>
        <text class="stat-label">已支付</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 订单列表 -->
    <view v-else class="order-list">
      <view v-if="orders.length === 0" class="empty-container">
        <text class="empty-text">今日暂无订单</text>
      </view>
      <view class="order-item" v-for="(order, index) in orders" :key="index">
        <view class="order-header">
          <view class="order-info">
            <text class="order-time">{{order.createTime}}</text>
            <text class="order-id">#{{order.id}}</text>
          </view>
          <text class="order-status" :class="order.status">{{getStatusText(order.status)}}</text>
        </view>
        
        <view class="order-content">
          <view class="order-products">
            <view class="product-item" v-for="(product, pIndex) in order.products" :key="pIndex">
              <view class="product-info">
                <image v-if="product.image" class="product-image" :src="getImageUrl(product.image)" mode="aspectFill"></image>
                <view class="product-details">
                  <text class="product-name">{{product.name}}</text>
                  <text v-if="product.description" class="product-desc">{{product.description}}</text>
                </view>
              </view>
              <view class="product-meta">
                <text class="product-quantity">x{{product.quantity}}</text>
                <text class="product-price">¥{{product.price}}</text>
              </view>
            </view>
          </view>
          
          <view class="order-summary">
            <text class="summary-text">共{{order.totalQuantity}}件商品</text>
            <text class="summary-price">¥{{order.totalPrice}}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { orderApi } from '../../utils/api.js'

export default {
  data() {
    return {
      loading: false,
      todayStats: {
        totalOrders: 0,
        totalIncome: 0,
        paidOrders: 0
      },
      orders: []
    }
  },
  
  onLoad() {
    this.loadTodayOrders()
  },
  
  onShow() {
    // 每次页面显示时重新加载数据
    this.loadTodayOrders()
  },
  
  methods: {
    // 获取当天订单数据
    async loadTodayOrders() {
      try {
        this.loading = true
        
        // 获取当前日期，格式为 yyyy-MM-dd
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        const dateStr = `${year}-${month}-${day}`
        
        console.log('获取当天订单，日期:', dateStr)
        
        const response = await orderApi.getOrdersByDate(dateStr)
        
        if (response.code === 200) {
          this.processOrderData(response.data)
        } else {
          console.error('获取订单失败:', response.message)
          uni.showToast({
            title: response.message || '获取订单失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取当天订单失败:', error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 处理订单数据
    processOrderData(orderItemDTOs) {
      if (!orderItemDTOs || orderItemDTOs.length === 0) {
        this.orders = []
        this.updateStats()
        return
      }
      
      // 按订单ID分组
      const orderMap = new Map()
      
      orderItemDTOs.forEach(dto => {
        const orderId = dto.customerOrder.orderId
        if (!orderMap.has(orderId)) {
          // 创建新的订单对象
          const order = {
            id: orderId,
            createTime: this.formatTime(dto.customerOrder.placeOrderTime),
            status: this.getOrderStatus(dto.customerOrder.orderStatus),
            customerName: '客户', // 暂时使用默认值
            customerPhone: '未知电话',
            totalQuantity: 0,
            totalPrice: dto.customerOrder.payableAmount || 0,
            products: []
          }
          orderMap.set(orderId, order)
        }
        
        // 添加订单项信息
        if (dto.customerOrderItem && dto.dishes && dto.dishes.length > 0) {
          const order = orderMap.get(orderId)
          const dish = dto.dishes[0] // 获取菜品信息
          
          order.products.push({
            dishId: dto.customerOrderItem.dishId,
            name: dish.dishName || `菜品${dto.customerOrderItem.dishId}`,
            quantity: dto.customerOrderItem.quantity || 1,
            price: dish.price || 0,
            image: dish.dishImage || '',
            description: dish.dishDescribe || ''
          })
          order.totalQuantity += dto.customerOrderItem.quantity || 1
        } else if (dto.customerOrderItem) {
          // 如果没有菜品信息，使用默认值
          const order = orderMap.get(orderId)
          order.products.push({
            dishId: dto.customerOrderItem.dishId,
            name: `菜品${dto.customerOrderItem.dishId}`,
            quantity: dto.customerOrderItem.quantity || 1,
            price: 0,
            image: '',
            description: ''
          })
          order.totalQuantity += dto.customerOrderItem.quantity || 1
        }
      })
      
      // 转换为数组并排序
      this.orders = Array.from(orderMap.values()).sort((a, b) => {
        return new Date(b.createTime) - new Date(a.createTime)
      })
      
      this.updateStats()
    },
    
    // 更新统计数据
    updateStats() {
      this.todayStats.totalOrders = this.orders.length
      this.todayStats.totalIncome = this.orders.filter(order => order.status === 'preparing').reduce((sum, order) => sum + order.totalPrice, 0)  // 只统计已支付订单的收入
      this.todayStats.paidOrders = this.orders.filter(order => order.status === 'preparing').length  // 统计已支付订单数
    },
    
    // 格式化时间
    formatTime(dateTime) {
      if (!dateTime) return '未知时间'
      
      const date = new Date(dateTime)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },
    
    // 获取订单状态
    getOrderStatus(status) {
      // 根据后端订单状态枚举转换为前端状态
      const statusMap = {
        'PAID': 'preparing',        // 已支付 -> 制作中
        'TO_BE_PAID': 'pending',    // 待支付 -> 待接单
        'CANCELED': 'rejected'      // 已取消 -> 已取消
      }
      return statusMap[status] || 'pending'
    },
    
    getStatusText(status) {
      const statusMap = {
        'pending': '待支付',      // TO_BE_PAID
        'preparing': '已支付',    // PAID
        'rejected': '已取消'      // CANCELED
      };
      return statusMap[status] || status;
    },
    
    handleOrder(order, action) {
      const actionText = {
        'accept': '接受',
        'reject': '取消'
      }
      
      uni.showModal({
        title: '提示',
        content: `确定要${actionText[action]}该订单吗？`,
        success: (res) => {
          if (res.confirm) {
            if (action === 'accept') {
              order.status = 'preparing';
            } else if (action === 'reject') {
              order.status = 'rejected';
            }
            this.updateStats() // 更新统计数据
            uni.showToast({
              title: '操作成功',
              icon: 'success'
            });
          }
        }
      });
    },

    getImageUrl(imagePath) {
      if (!imagePath) {
        return '';
      }
      // 如果已经是完整的URL，直接返回
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath;
      }
      // 添加OSS前缀
      return `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${imagePath}`;
    }
  }
}
</script>

<style>
.today-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  background-color: #ffffff;
  padding: 30rpx 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.order-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-time {
  font-size: 28rpx;
  color: #333;
}

.order-id {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  font-size: 26rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.order-status.pending {
  color: #ff4d4f;
  background-color: #fff1f0;
}

.order-status.preparing {
  color: #1890ff;
  background-color: #e6f7ff;
}

.order-status.rejected {
  color: #999;
  background-color: #f5f5f5;
}

.order-content {
  margin-bottom: 20rpx;
}

.order-products {
  margin-bottom: 20rpx;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
  padding: 15rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

.product-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin-right: 15rpx;
  background-color: #f0f0f0;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.product-desc {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.product-quantity {
  font-size: 26rpx;
  color: #666;
  background-color: #e6f7ff;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.product-price {
  font-size: 28rpx;
  color: #C70209;
  font-weight: bold;
}

.order-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.summary-text {
  font-size: 26rpx;
  color: #666;
  margin-right: 20rpx;
}

.summary-price {
  font-size: 32rpx;
  color: #C70209;
  font-weight: bold;
}

.order-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.order-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  font-size: 24rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  border-radius: 25rpx;
  background-color: #C70209;
  color: #ffffff;
}

.action-btn.reject {
  background-color: #f5f5f5;
  color: #666;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style> 